package b1.mobile.blackberry.ui.component;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.TouchEvent;
import net.rim.device.api.ui.TouchGesture;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.XYRect;
import net.rim.device.api.ui.component.LabelField;

public class ToggleField extends Manager {

	boolean _value = false;
	LabelField _label = new LabelField("", Field.NON_FOCUSABLE);
	Font labelFont = getFont();
	
	public ToggleField(long style){
		super(style);
		
		
		try{
			FontFamily ff = FontFamily.forName("Alpha Sans");
			labelFont = ff.getFont(Font.BOLD, 6, Ui.UNITS_pt);
		} catch (ClassNotFoundException e){
			
		}
		
		_label.setFont(labelFont);
		
		_value = false;		
		this.add(_label);
	}
	
	protected void sublayout(int width, int height) {
		// TODO Auto-generated method stub
		
		layoutChild(_label, labelFont.getAdvance(_label.getText()), labelFont.getHeight());
		setPositionChild(_label, (_value ? 10 : 54), 8);
		
		setExtent(getPreferredWidth(), getPreferredHeight());
	}

	protected void paint(Graphics g) {
		_label.setText(_value ? "ON" : "OFF");
		getManager().invalidate();
		super.paint(g);
	}
	
	protected void subpaint(Graphics g) {
		g.setColor(0x00ffffff);
		paintChild(g, _label);
	
	}
	
	public int getPreferredWidth() {
		return 97;
	}
	
	public int getPreferredHeight() {
		return 36;
	}
	
	public boolean isFocusable() {
		return true;
	}
	
	protected void paintBackground(Graphics g) {		
		StringBuffer bgName = new StringBuffer("_Toggle_");
		bgName.append(_value ? "ON_" : "OFF_");
		bgName.append(isFocus() ? "Focus_" : "");
		bgName.append("bg.png");
		
		Bitmap bgImg = Bitmap.getBitmapResource(bgName.toString());		
		
		g.drawBitmap(new XYRect(0, 0, getExtent().width, getExtent().height), bgImg, 0, 0);
		
		super.paintBackground(g);
	}
	
	public boolean isSelectable() {
		return true;
	}
	
	public boolean isSelecting() {
		return super.isSelecting();
	}
	
	protected boolean trackwheelClick(int status, int time) {
		_value = !_value;
		return super.trackwheelClick(status, time);
	}
	
//	protected boolean touchEvent(TouchEvent message) {
//		if(message.getGesture().getEvent() == TouchGesture.TAP){
//			_value = !_value;
//		}
//		return super.touchEvent(message);
//	}
	
	public void setBoolean(boolean bool){
		_value = bool;
		invalidate();
	}
	
	public boolean getBoolean(){
		return _value;
	}
}
